package com.hollycrm.ahunicom.dwr.facade;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.hibernate.Query;

import org.springframework.orm.hibernate.support.HibernateDaoSupport;

public class PageModel extends HibernateDaoSupport{
	private int rows;
	private Map map=new HashMap();
    private List currentPgData;
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public Map getPaginationInfo(String currnetPage,String hql,String operatorSign)throws Exception{
		String hq=hql.substring(hql.indexOf("from"),hql.length());
	    int allRows=this.getHibernateTemplate().find(hq).size();
	    int allPages=allRows%rows==0?allRows/rows:allRows/rows+1;
	    int currentPg=Integer.valueOf(currnetPage).intValue();
	    Query query=this.getHibernateTemplate().getSessionFactory().openSession().createQuery(hql);
	    if(operatorSign.equals("first")){
	    	currentPg=1;
	    }
	    if(operatorSign.equals("last")){
	    	currentPg=allPages;
	    }
	    if(operatorSign.equals("before")){
	    	currentPg=currentPg-1;
	    	if(currentPg==0){
	    		currentPg=1;
	    	}
	    }
	    if(operatorSign.equals("next")){
	    	currentPg=currentPg+1;
	    	if(currentPg==allPages+1){
	    		currentPg=allPages;
	    	}
	    }
	    currentPgData=getCurrentData(currentPg,query,allPages);
	    map.put("allRows",String.valueOf(allRows));
	    map.put("allPages",String.valueOf(allPages));
	    map.put("currentPg",String.valueOf(currentPg));
	    map.put("currentPageData",currentPgData);
	    map.put("hql",hql);
	    return map;
	}
	private List getCurrentData(int currentPg,Query query,int allPages)throws Exception{
		 if(currentPg<=1){
		    	query.setFirstResult(1);
		    	query.setMaxResults(rows);
		    }
		    if(currentPg>=allPages){
		    	query.setFirstResult((allPages-1)*rows);
		    	query.setMaxResults(rows);
		    }
		    if(1<currentPg&&allPages>currentPg){
		    	query.setFirstResult((currentPg-1)*rows);
		        query.setMaxResults(rows);
		    }
		  return query.list();
		    
	}
	
    
}